/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package window;

import authentication.EncryptionType;
import busEvents.AddEmailRecipient;
import com.adamtaft.eb.EventBusService;
import com.adamtaft.eb.EventHandler;
import data.contact.ContactFolder;
import java.awt.Component;
import javax.swing.JFrame;
import windowComponents.EmailInputField;
import com.inet.editor.*;
import connection.SMTPAccount;
import data.AccountData;
import data.Data;
import data.email.AccountType;
import data.email.EmailAddress;
import data.email.EmailMessage;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.util.Calendar;
import java.util.LinkedHashSet;
import java.util.Set;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.mail.Message;
import javax.swing.JPanel;
import windowComponents.AttachmentAddPanel;

/**
 *
 * @author Arcanis
 */
public class NewEmailPanel extends javax.swing.JPanel {

    private BaseEditor ed;
    private ContactFolder folder = null;
    private JFrame parent = null;
    private JPanel fillPane = new JPanel();
    private JPanel fillPane1 = new JPanel();
    private Data data = null;

    public NewEmailPanel() {
        initComponents();
    }

    /**
     * Creates new form NewEmailPanel
     */
    public NewEmailPanel(JFrame frame) {
        initComponents();
        ed = new BaseEditor(true, true, true, true);
        jPanel4.add(ed);
        parent = frame;

        jPanel2.setLayout(new GridBagLayout());
        jPanel5.setLayout(new GridBagLayout());

        clearEmail();

        EventBusService.subscribe(this);
    }

    private void addEmptyAttachmentInputPanel() {
        jPanel5.remove(fillPane1);
        AttachmentAddPanel f = new AttachmentAddPanel();
        f.registerValueChanged(this);

        GridBagConstraints c = new GridBagConstraints();
        c.weightx = 0.5;
        c.fill = GridBagConstraints.HORIZONTAL;
        c.gridx = 0;
        c.gridy = jPanel5.getComponentCount();
        jPanel5.add(f, c);

        c.weighty = 1;
        c.fill = GridBagConstraints.BOTH;
        c.gridx = 0;
        c.gridy = jPanel5.getComponentCount();
        jPanel5.add(fillPane1, c);
    }

    private void addEmptyEmailInputPanel() {
        jPanel2.remove(fillPane);
        EmailInputField f = new EmailInputField(parent);
        f.registerValueChanged(this);

        if (folder != null) {
            f.setContactFolder(folder);
        }

        GridBagConstraints c = new GridBagConstraints();
        c.weightx = 0.5;
        c.fill = GridBagConstraints.HORIZONTAL;
        c.gridx = 0;
        c.gridy = jPanel2.getComponentCount();

        jPanel2.add(f, c);

        c.weighty = 1;
        c.fill = GridBagConstraints.BOTH;
        c.gridx = 0;
        c.gridy = jPanel2.getComponentCount();
        jPanel2.add(fillPane, c);
    }

    public void checkAndAddEmpty() {
        Set<EmailInputField> remain = new LinkedHashSet<>();
        EmailInputField focused = null;
        for (Component comp : jPanel2.getComponents()) {
            if (comp instanceof EmailInputField) {
                if (((EmailInputField) comp).isTextFieldFocused()) {
                    focused = (EmailInputField) comp;
                }
                EmailInputField em = (EmailInputField) comp;
                if (!em.getValue().equals(new EmailAddress(""))) {
                    remain.add(em);
                }
            }
        }
        jPanel2.removeAll();

        GridBagConstraints c = new GridBagConstraints();
        c.weightx = 0.5;
        c.fill = GridBagConstraints.HORIZONTAL;
        c.gridx = 0;
        c.gridy = 0;
        for (EmailInputField in : remain) {
            jPanel2.add(in, c);
            c.gridy++;
        }

        addEmptyEmailInputPanel();

        jPanel2.invalidate();
        jPanel2.updateUI();
        jPanel2.repaint();
        
        if(focused != null){
            focused.setFocusToTextField();
        }        
    }

    public void checkAndAddEmptyAttachments() {
        Set<AttachmentAddPanel> remain = new LinkedHashSet<>();
        for (Component comp : jPanel5.getComponents()) {
            if (comp instanceof AttachmentAddPanel) {
                AttachmentAddPanel em = (AttachmentAddPanel) comp;
                if (!em.getValue().equals("")) {
                    remain.add(em);
                }
            }
        }

        jPanel5.removeAll();

        GridBagConstraints c = new GridBagConstraints();
        c.weightx = 0.5;
        c.fill = GridBagConstraints.HORIZONTAL;
        c.gridx = 0;
        c.gridy = 0;
        for (AttachmentAddPanel in : remain) {
            jPanel5.add(in, c);
            c.gridy++;
        }

        addEmptyAttachmentInputPanel();

        jPanel5.invalidate();
        jPanel5.updateUI();
        jPanel5.repaint();
    }

    public void setContactFolder(ContactFolder folder) {
        this.folder = folder;
        for (Component comp : jPanel2.getComponents()) {
            if (comp instanceof EmailInputField) {
                ((EmailInputField) comp).setContactFolder(folder);
            }
        }
    }

    @EventHandler
    public void handleAddEmailRecipient(AddEmailRecipient rec) {
        EmailInputField ei = new EmailInputField(parent, rec);
        if (folder != null) {
            ei.setContactFolder(folder);
        }
        jPanel2.add(ei);
        checkAndAddEmpty();
    }

    private void clearEmail() {
        jPanel2.removeAll();
        addEmptyEmailInputPanel();
        jPanel5.removeAll();
        addEmptyAttachmentInputPanel();

        jTextField2.setText("");
        ed.setText("", true);

        updateUI();
        invalidate();
        repaint();

        ed.requestFocus();
    }

    private void sendEmail() {
        System.out.println("Odesílám email");

        EmailMessage msg = new EmailMessage();
        msg.setBody(ed.getText());
        msg.setDate(Calendar.getInstance().getTime());
        msg.setSubject(jTextField2.getText());

        System.out.println("Adresy:");

        for (Component comp : jPanel2.getComponents()) {
            if (comp instanceof EmailInputField) {
                EmailInputField field = ((EmailInputField) comp);
                if (!field.getValue().equals(new EmailAddress(""))) {
                    EmailAddress ad = new EmailAddress(field.getValue().getAddress().trim().split(" ")[0]);
                    if (field.getType().equals(Message.RecipientType.TO)) {
                        System.out.println("TO: " + ad.getAddress());
                        msg.addTo(ad);
                    } else if (field.getType().equals(Message.RecipientType.CC)) {
                        System.out.println("CC: " + ad.getAddress());
                        msg.addCC(ad);
                    } else {
                        System.out.println("BCC: " + ad.getAddress());
                        msg.addBcc(ad);
                    }
                }
            }
        }
        if (data != null) {
            try {
                data.sendEmail(msg);
                clearEmail();
            } catch (Exception ex) {
                Logger.getLogger(NewEmailPanel.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
        System.out.println("End ddesilani mailu");
    }

    public void setData(Data data) {
        this.data = data;
    }

    /**
     * This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jSplitPane2 = new javax.swing.JSplitPane();
        jPanel1 = new javax.swing.JPanel();
        jScrollPane2 = new javax.swing.JScrollPane();
        jPanel2 = new javax.swing.JPanel();
        jPanel3 = new javax.swing.JPanel();
        jScrollPane1 = new javax.swing.JScrollPane();
        jPanel5 = new javax.swing.JPanel();
        jLabel2 = new javax.swing.JLabel();
        jTextField2 = new javax.swing.JTextField();
        jButton1 = new javax.swing.JButton();
        jButton2 = new javax.swing.JButton();
        jPanel4 = new javax.swing.JPanel();

        jSplitPane2.setDividerLocation(250);

        jPanel1.setLayout(new java.awt.GridLayout(0, 1));

        jPanel2.setLayout(new java.awt.GridLayout(0, 1));
        jScrollPane2.setViewportView(jPanel2);

        jPanel1.add(jScrollPane2);

        jSplitPane2.setLeftComponent(jPanel1);

        jPanel3.setLayout(new java.awt.GridLayout(0, 1));

        jPanel5.setLayout(new java.awt.GridLayout(0, 1));
        jScrollPane1.setViewportView(jPanel5);

        jPanel3.add(jScrollPane1);

        jSplitPane2.setRightComponent(jPanel3);

        jLabel2.setText("Předmět:");

        jButton1.setIcon(new javax.swing.ImageIcon(getClass().getResource("/icons/send_mail.png"))); // NOI18N
        jButton1.setToolTipText("Odeslat Email");
        jButton1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton1ActionPerformed(evt);
            }
        });

        jButton2.setIcon(new javax.swing.ImageIcon(getClass().getResource("/icons/Delete-Icon.png"))); // NOI18N
        jButton2.setToolTipText("Vymazat Email");
        jButton2.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton2ActionPerformed(evt);
            }
        });

        jPanel4.setLayout(new java.awt.GridLayout(1, 0));

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
        this.setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jSplitPane2, javax.swing.GroupLayout.DEFAULT_SIZE, 336, Short.MAX_VALUE)
            .addGroup(layout.createSequentialGroup()
                .addComponent(jLabel2)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jTextField2))
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addGap(0, 0, Short.MAX_VALUE)
                .addComponent(jButton2)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jButton1))
            .addComponent(jPanel4, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addComponent(jSplitPane2, javax.swing.GroupLayout.PREFERRED_SIZE, 100, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel2)
                    .addComponent(jTextField2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jPanel4, javax.swing.GroupLayout.DEFAULT_SIZE, 121, Short.MAX_VALUE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jButton1)
                    .addComponent(jButton2)))
        );
    }// </editor-fold>//GEN-END:initComponents

    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed
        sendEmail();
    }//GEN-LAST:event_jButton1ActionPerformed

    private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton2ActionPerformed
        clearEmail();
    }//GEN-LAST:event_jButton2ActionPerformed
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton jButton1;
    private javax.swing.JButton jButton2;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JPanel jPanel2;
    private javax.swing.JPanel jPanel3;
    private javax.swing.JPanel jPanel4;
    private javax.swing.JPanel jPanel5;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JScrollPane jScrollPane2;
    private javax.swing.JSplitPane jSplitPane2;
    private javax.swing.JTextField jTextField2;
    // End of variables declaration//GEN-END:variables
}
